package com.example.heipictureserver.mangger.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.example.heipictureserver.exception.BusinessException;
import com.example.heipictureserver.exception.ErrorCode;
import com.example.heipictureserver.exception.ThrowUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

/*
 *@Description url图片上传
 *@Author bwg
 *@Date 2025/1/23 22:05
 */
@Service
public class UrlPictureUpload extends PictureUploadTemplate {
    private static final long OneMb = 1024 * 1024;

    private static final long MAX_SIZE = 5 * OneMb;
    @Override
    protected void processFile(Object inputSource, File file) {
        String fileUrl = (String) inputSource;
        // 下载文件到临时文件
        HttpUtil.downloadFile(fileUrl, file);
    }

    @Override
    protected void validPicture(Object inputSource) {
        String fileUrl = (String) inputSource;
        // 1.非空
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "文件地址不能为空");
        // 2.协议
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件地址不合法");
        }
        // 3.HEAD请求
        ThrowUtils.throwIf(!fileUrl.startsWith("http")&&!fileUrl.startsWith("https"), ErrorCode.PARAMS_ERROR, "文件协议不支持");
        // 4.文件后缀
        try (HttpResponse httpResponse = HttpUtil.createRequest(Method.HEAD, fileUrl).execute()) {
            if (httpResponse.getStatus() == HttpStatus.HTTP_OK) {
                return;
            }
            // 文件存在,后缀校验
            String contentType = httpResponse.header("Content-Type");
            if (StrUtil.isBlank(contentType)) {
                final List<String> ALLOW_FORMAT_LIST = Arrays.asList("image/jpeg", "image/png", "image/jpg", "image/webp");
                ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(contentType.toLowerCase()), ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
            String contentLengthStr = httpResponse.header("Content-Length");
            if (StrUtil.isBlank(contentLengthStr)) {
                try {
                    long fileSize = Long.parseLong(contentLengthStr);
                    ThrowUtils.throwIf(fileSize > MAX_SIZE, ErrorCode.PARAMS_ERROR, "文件大小不能超过5MB");
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小错误");
                }
            }
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件地址错误");
        }
    }

    @Override
    protected String getOriginalFilename(Object inputSource) {
        return FileUtil.mainName((String) inputSource);
    }
}
